package org.hospital.controller;

import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hospital.entity.Client;
import org.hospital.entity.Employee;
import org.hospital.entity.Log;
import org.hospital.service.LogService;
import org.hospital.service.MedicalCardService;
import org.hospital.service.PermissionService;
import org.hospital.service.UserService;
import org.hospital.util.Constant;
import org.hospital.util.DateUtil;
import org.hospital.util.Md5Util;
import org.hospital.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

@Controller
@RequestMapping(value = "userController")
@SessionAttributes(value = "employee", types = Employee.class)
public class UserController {

	@Autowired
	private UserService uService;
	@Autowired
	private PermissionService pmService;
	@Autowired
	private LogService lService;
	@Autowired
	private MedicalCardService mService;

	/**
	 * 创建员工 {positionId,departmentId,clinicId,employeeCode,account,pwd,name,
	 * ?age,?sex,isDomain }
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createEmployee", produces = "text/json;charset=utf-8")
	public String createEmployee(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_EMPLOYEE.getName(), 5)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		try {
			// 获取数据
			int positionId = Integer.parseInt(req.getParameter("positionId"), 10);
			int departmentId = Integer.parseInt(req.getParameter("departmentId"), 10);
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			String employeeCode = req.getParameter("employeeCode");
			String account = req.getParameter("account");
			String pwd = Md5Util.getMd5(req.getParameter("pwd"));
			String name = req.getParameter("name");
			String age = req.getParameter("age");
			String sex = req.getParameter("sex");
			String birthdate = req.getParameter("birthdate");
			int isDomain = Integer.parseInt(req.getParameter("isDomain"), 10);
			int isOnJob = Integer.parseInt(req.getParameter("isOnJob"), 10);

			//long birthdate = DateUtil.getShortDateLong(req.getParameter("birthdate"));
			// 验证合法性
			if (employeeCode == null || account == null || pwd == null || name == null) {
				return StringUtil.setResult(401, "缺少必要参数", "");
			}
			// 插入数据库
			Employee e = new Employee();
			e.setPositionId(positionId);
			e.setDepartmentId(departmentId);
			e.setClinicId(clinicId);
			e.setEmployeeCode(employeeCode);
			e.setAccount(account);
			e.setPwd(pwd);
			e.setName(name);
			if (null != age) {
				e.setAge(Integer.parseInt(age, 10));
			}
			if (null != birthdate && "" != birthdate) {
				e.setBirthdate(new Timestamp(DateUtil.getShortDateLong(birthdate)));
			}
			if (null != sex) {
				if (sex.equals("0")) {
					e.setSex("0");
				} else if (sex.equals("1")) {
					e.setSex("1");
				} else {
					return StringUtil.setResult(403, "sex参数有误", "");
				}
			}
			e.setRegisterTime(new Timestamp(DateUtil.getNowLong()));

			e.setStatus(1);
			e.setIsOnJob(isOnJob);
			e.setIsDomain(isDomain);

			System.out.println("userController.e : " + JSON.toJSONString(e));

			String result = uService.addEmployee(e);

			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_EMPLOYEE.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(e));
			lService.addEntity(log);

			return result;

		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 创建客户
	 * 
	 * @param req
	 *            {name,status,?identity,?sex,?phone,?birthdate,?nation,?marriage,?occupation}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createClient", produces = "text/json;charset=utf-8")
	public String createClient(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_CLIENT.getName(), 1)) {
			return StringUtil.setResult(402, "权限不足", "");
		}
		List<Client> cList = uService.isRepeatIdentity(req.getParameter("identity"));
		if (cList != null && !cList.isEmpty()) {
			return StringUtil.setResult(411, "身份证已存在", "");
		}
		try {
			// 获取参数
			String name = req.getParameter("name");
			String identity = req.getParameter("identity");
			String sex = req.getParameter("sex");
			String phone = req.getParameter("phone");
			String birthdate = req.getParameter("birthdate");
			String nation = req.getParameter("nation");
			String marriage = req.getParameter("marriage");
			String occupation = req.getParameter("occupation");
			int status = Integer.parseInt(req.getParameter("status"), 10);

			Client client = new Client();
			client.setName(name);
			if (null != identity && identity.length() > 0) {
				client.setIdentity(identity);
			}
			if (null != sex && sex.length() > 0) {
				client.setSex(Integer.parseInt(sex, 10));
			}
			if (null != phone && phone.length() > 0) {
				client.setPhone(phone);
			}
			if (null != birthdate && birthdate.length() > 0) {
				client.setBirthdate(new Timestamp(DateUtil.getShortDateLong(birthdate)));
			}
			if (null != nation && nation.length() > 0) {
				client.setNation(nation);
			}
			if (null != marriage && marriage.length() > 0) {
				client.setMarriage(Integer.parseInt(marriage, 10));
			}
			if (null != occupation && occupation.length() > 0) {
				client.setOccupation(occupation);
			}
			client.setRegisterTime(new Timestamp(DateUtil.getNowLong()));
			client.setStatus(status);

			System.out.println("userController.createClient.client" + JSON.toJSONString(client));
			// 插入数据
			client = uService.addClient(client);
			if (null == client) {
				return StringUtil.setResult(501, "数据库操作失败", "");
			}

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_CLIENT.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(client));
			lService.addEntity(log);

			return StringUtil.setResult(200, "操作成功", "");

		} catch (Exception e) {
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 修改员工资料 只有管理员能够修改资料
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/alterEmployee", produces = "text/json;charset=utf-8")
	public String alterEmployee(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.ALTER_EMPLOYEE.getName(), 5)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		try {
			// 获取参数
			int employeeId = Integer.parseInt(req.getParameter("employeeId"), 10);
			int positionId = Integer.parseInt(req.getParameter("positionId"), 10);
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			int departmentId = Integer.parseInt(req.getParameter("departmentId"), 10);
			String employeeCode = req.getParameter("employeeCode");
			String name = req.getParameter("name");
			String age = req.getParameter("age");
			String sex = req.getParameter("sex");
			String birthdate = req.getParameter("birthdate");
			int isOnJob = Integer.parseInt(req.getParameter("isOnJob"), 10);
			int isDomain = Integer.parseInt(req.getParameter("isDomain"), 10);

			// 验证基本合法性
			// 职位、门诊、科室参数合法性在前端给予选择时给予有效参数
			// employeeCode 合法性在service层验证
			if (name == null || name == "") {
				return StringUtil.setResult(403, "name参数有误", "");
			}
			if (isOnJob != 0 && isOnJob != 1) {
				return StringUtil.setResult(403, "isOnJob参数有误", "");
			}
			if (isDomain != 0 && isDomain != 1) {
				return StringUtil.setResult(403, "isDomain参数有误", "");
			}
			
			
			Employee employee = new Employee();
			employee.setEmployeeId(employeeId);
			employee.setClinicId(clinicId);
			employee.setDepartmentId(departmentId);
			employee.setPositionId(positionId);
			employee.setEmployeeCode(employeeCode);
			employee.setName(name);
			if(null != age && "" != age) {
				employee.setAge(Integer.parseInt(age, 10));
			}
			if(null != birthdate && "" != birthdate) {
				employee.setBirthdate(new Timestamp(DateUtil.getShortDateLong(birthdate)));
			}
			if(null != sex && "" != sex) {
				int sexInt = Integer.parseInt(sex, 10);
				if (sexInt == 0) {
					employee.setSex("0");
				} else if (sexInt == 1) {
					employee.setSex("1");
				} else {
					return StringUtil.setResult(403, "sex参数有误", "");
				}
			}
			employee.setIsOnJob(isOnJob);
			employee.setIsDomain(isDomain);
			
			//数据库操作
			String result = uService.saveEmployee(employee);

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.ALTER_EMPLOYEE.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(employee));
			lService.addEntity(log);

			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 根据姓名模糊查询客户
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/searchClient", produces = "text/json;charset=utf-8")
	public String searchClient(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		
		String searchParam = req.getParameter("searchParam"); //搜索参数
		JSONArray resultJA = uService.searchClientByName(searchParam);
		//System.out.println("searchClient.searchParam : "+searchParam);
		//System.out.println("searchClient.resultJA"+resultJA.toJSONString());
		
		if (resultJA == null || resultJA.size() == 0) {
			return StringUtil.setResult(414, "数据为空", "");
		}
		return StringUtil.setResult(200, "操作成功", resultJA);
	}

	/**
	 * 根据身份证获取客户信息
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getClientByIdentity", produces = "text/json;charset=utf-8")
	public String getClientByIdentity(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}

		String identity = req.getParameter("identity");
		JSONArray resultJA = uService.getClientByIdentity(identity);
		if (resultJA == null || resultJA.size() == 0) {
			return StringUtil.setResult(414, "数据为空", "");
		}
		return StringUtil.setResult(200, "操作成功", resultJA);
	}

	/**
	 * 获取门诊下在职的医生信息
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getClinicEmployee", produces = "text/json;charset=utf-8")
	public String getClinicEmployee(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		try {
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);

			JSONArray resultJA = uService.getClinicEmployee(clinicId);
			if (resultJA == null || resultJA.size() == 0) {
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功",resultJA.size(),resultJA);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 获取科室下在职的医生信息
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getDepartmentEmployee", produces = "text/json;charset=utf-8")
	public String getDepartmentEmployee(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		try {
			int departmentId = Integer.parseInt(req.getParameter("departmentId"), 10);

			JSONArray resultJA = uService.getDepartmentEmployee(departmentId);
			if (resultJA == null || resultJA.size() == 0) {
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功", resultJA);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 获取门诊负责人人选
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getClinicPrincipal", produces = "text/json;charset=utf-8")
	public String getClinicPrincipal(WebRequest req, HttpSession session) {
		// 获取数据
		try {
			List<Employee> eList = uService.getClinicPrincipal();
			if (eList == null || eList.size() == 0) {
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功", eList);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 获取科室负责人人选
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getDepartmentPrincipal", produces = "text/json;charset=utf-8")
	public String getDepartmentPrincipal(WebRequest req, HttpSession session) {
		// 获取数据
		try {
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);

			List<Employee> eList = uService.getDepartmentPrincipal(clinicId);
			if (eList == null || eList.size() == 0) {
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功", eList);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 获取员工数据
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/employeeAchieveData", produces = "text/json;charset=utf-8")
	public String achieveData(WebRequest req, HttpSession session) {
		// 检测用户权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登录", "");
		}
		try {
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			int pageIndex = Integer.parseInt(req.getParameter("pageIndex"), 10);
			int pageSize = Integer.parseInt(req.getParameter("pageSize"), 10);
			//System.out.println("pageIndex: "+pageIndex);
			//System.out.println("pageNumber: "+pageSize);
			JSONArray eList = uService.getEmployeeData(clinicId,pageIndex,pageSize);
			if (eList == null || eList.size() == 0) {
				return StringUtil.setResult(414, "数据为空", "");
			}
			
			Long number = uService.getClinicEmployeeNumber(clinicId);
			
			//System.out.println("employeeAchieveData : "+StringUtil.setResult(200, "操作成功",number,eList));
			
			return StringUtil.setResult(200, "操作成功",number,eList);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}

	/**
	 * 根据检索获取员工数据
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/searchEmployeeData", produces = "text/json;charset=utf-8")
	public String searchData(WebRequest req) {
		try {
			int clinicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			String search = req.getParameter("search");
			JSONArray eList = uService.getSearchEmployeeData(clinicId, search);
			if (eList == null || eList.size() == 0) {
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功", eList);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
	
	/**
	 * 根据员工id，检索旧密码是否正确
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/employeeFindById", produces = "text/json;charset=utf-8")
	public String employeeFindById(WebRequest req) {
		try {
			int employeeId = Integer.parseInt(req.getParameter("employeeId"), 10);
			String oldPwd = Md5Util.getMd5(req.getParameter("oldPwd"));
			Employee employee = uService.getEmployeeById(employeeId);
			if (employee == null) {
				return StringUtil.setResult(414, "账号过期", "");
			}else{
				if(oldPwd.equals(employee.getPwd())){
					return StringUtil.setResult(200, "密码正确", employee);
				}
				return StringUtil.setResult(400, "密码错误", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
	
	/**
	 * 修改密码
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateEmployeePwd", produces = "text/json;charset=utf-8")
	public String updateEmployeePwd(WebRequest req){
		try{
			int employeeId = Integer.parseInt(req.getParameter("employeeId"),10);
			String pwd = req.getParameter("newPassword");
			Employee e = uService.getEmployeeById(employeeId);
			e.setPwd(Md5Util.getMd5(pwd));
			return uService.saveEmployee(e);
		}catch(Exception e){
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
	/**
	 * 获取病人信息
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getClient",produces="text/json;charset=utf-8")
	public String getClient(WebRequest req,HttpSession session){
		try{
			
			int pageIndex = Integer.parseInt(req.getParameter("pageIndex"), 10);
			int pageSize = Integer.parseInt(req.getParameter("pageSize"), 10);
			JSONArray resultJA = uService.getAllClient(pageIndex,pageSize);
			
			if(resultJA == null || resultJA.size() == 0){
				return StringUtil.setResult(414, "数据为空", "");
			}
			Long number = uService.getClientNumber();
			return StringUtil.setResult(200, "操作成功",number, resultJA);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
	
	/**
	 *修改病人信息
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updateClient",produces="text/json;charset=utf-8")
	public String updateClient(WebRequest req,HttpSession session){
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		String identityNum=req.getParameter("identityNum");
		if(identityNum.equals("0")){
			List<Client> cList=uService.isRepeatIdentity(req.getParameter("identity"));
			if(cList!=null && !cList.isEmpty()){
				return StringUtil.setResult(411, "身份证已存在", "");
			}
		}
		try{
			Client client=new Client();
			int clientId = Integer.parseInt(req.getParameter("clientId"));
			String name = req.getParameter("name");
			String identity = req.getParameter("identity");
			String sex = req.getParameter("sex");
			String phone = req.getParameter("phone");
			String birthdate = req.getParameter("birthdate");
			String nation = req.getParameter("nation");
			String marriage = req.getParameter("marriage");
			String occupation = req.getParameter("occupation");
			int status = Integer.parseInt(req.getParameter("status"), 10);
			client.setClientId(clientId);
			if (null != name){
				client.setName(name);
			}
			if (null != identity) {
				client.setIdentity(identity);
			}
			if (null != sex) {
				client.setSex(Integer.parseInt(sex, 10));
			}
			if (null != phone) {
				client.setPhone(phone);
			}
			if (null != birthdate) {
				client.setBirthdate(new Timestamp(DateUtil.getShortDateLong(birthdate)));
			}
			if (null != nation) {
				client.setNation(nation);
			}
			if (null != marriage) {
				client.setMarriage(Integer.parseInt(marriage, 10));
			}
			if (null != occupation) {
				client.setOccupation(occupation);
			}
			client.setRegisterTime(new Timestamp(DateUtil.getNowLong()));
			client.setStatus(status);
			Client c = uService.saveClient(client);
			
			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_CLIENT.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(client));
			lService.addEntity(log);
			
			if(c!=null){
				return StringUtil.setResult(200, "更改成功", "");
			}else{
				return StringUtil.setResult(501, "数据库操作失败", "");
			}
		}catch(Exception e){
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
}
